//
//  FSScrollerView.m
//  fanshu
//
//  Created by mh on 16/3/28.
//  Copyright © 2016年 FS. All rights reserved.
//
static int const mScrollerImageCount = 3;
#define mScrollerViewWidth self.scrollView.frame.size.width
#define mScrollerViewHeidth self.scrollView.frame.size.height
#import "FSScrollerView.h"
#import "FSButton.h"
@interface FSScrollerView ()<UIScrollViewDelegate>
@property (weak, nonatomic) UIScrollView *scrollView;
@property (weak, nonatomic) UIPageControl *pageView;

@property (weak, nonatomic) NSTimer *timer;
@end
@implementation FSScrollerView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        //初始化控件
        UIScrollView *scrollerView = [[UIScrollView alloc] init];
        [self addSubview:scrollerView];
        self.scrollView = scrollerView;
        
        UIPageControl *pageView = [[UIPageControl alloc] init];
        [self addSubview:pageView];
        self.pageView = pageView;
        
        self.scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        self.pageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin;
        self.scrollView.delegate = self;
        self.scrollView.pagingEnabled = YES;
        self.scrollView.showsVerticalScrollIndicator = NO;
        self.scrollView.showsHorizontalScrollIndicator = NO;
        self.pageView.hidesForSinglePage = YES;
    }
    return self;
}

- (instancetype)initWithArray:(NSArray<NSString *> *)imageArray
{
    self = [super init];
    if (self) self.imageArray = imageArray;
    return self;
}
- (void)layoutSubviews{
    [super layoutSubviews];
// update the width of imageView if the width of scrollview is change
    for (int i = 0; i < mScrollerImageCount; i ++) {
    UIImageView *imageView = self.scrollView.subviews[i];
    CGRect frame = imageView.frame;
    frame.origin.x = i * mScrollerViewWidth;
    imageView.frame = frame;
}
    self.scrollView.frame = CGRectMake(0, 0, mScrollerViewWidth, mScrollerViewHeidth);
    self.pageView.center = CGPointMake(self.scrollView.centerX, self.scrollView.height * 0.95);
// set up the contentSize once again
self.scrollView.contentSize = CGSizeMake(mScrollerImageCount * mScrollerViewWidth, 0);
[self setCurrentImage:self.pageView.currentPage animate:YES];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    // calculate the page'offset
    NSInteger page = (int)((self.scrollView.contentOffset.x - mScrollerViewWidth) / mScrollerViewWidth);
    // set currenPage
    NSInteger currentPage = self.pageView.currentPage + page;
    if (currentPage == self.imageArray.count) currentPage = 0;
    if (currentPage == -1) currentPage = self.imageArray.count - 1;
    self.pageView.currentPage = currentPage;
    [self setCurrentImage:self.pageView.currentPage animate:NO];
}

#pragma mark -  set with date
- (void)setImageArray:(NSArray<NSString *> *)imageArray{
    _imageArray = imageArray;
    [self initAboutImageView];
    // 2.set contentSize of three image
    self.scrollView.contentSize = CGSizeMake(mScrollerImageCount * mScrollerViewWidth, 0);
    // 3.set numberOfPages
    self.pageView.numberOfPages = _imageArray.count;
    [self startTimer];
}

- (void)initAboutImageView{
    //0.clear the old arrar
    [self.scrollView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    // 1.add image
    for (int i = 0; i < mScrollerImageCount; i ++) {
          //这里换成button
        FSButton *imageView = [[FSButton alloc] init];
        imageView.autoresizingMask =  UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        imageView.frame = CGRectMake(i * mScrollerViewWidth, 0, mScrollerViewWidth, mScrollerViewHeidth);
        imageView.imageView.contentMode = UIViewContentModeScaleAspectFit;
        /*
        UIImageView *imageView = [[UIImageView alloc] init];
        imageView.autoresizingMask =  UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        imageView.frame = CGRectMake(i * mScrollerViewWidth, 0, mScrollerViewWidth, mScrollerViewHeidth);
        imageView.contentMode = UIViewContentModeScaleAspectFit;
         */
        [self.scrollView addSubview:imageView];
        [imageView addTarget:self action:@selector(btnOnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    //setup the image in begin
    self.pageView.currentPage = 0;
    [self setCurrentImage:self.pageView.currentPage animate:YES];
}

#pragma  mark - 设置图片   
- (void)setCurrentImage:(NSInteger)imageIndex animate:(BOOL)ani{
    int index = (int)imageIndex;
    if (0 == index) {   //the first image
        //get the first ImageView
        FSButton *imageView = self.scrollView.subviews[index];
        //set up the last iamge
        [imageView setImage:[UIImage imageNamed:_imageArray[self.imageArray.count - 1]] forState:UIControlStateNormal];
        for (int i = 0; i< mScrollerImageCount - 1; i ++) {
            FSButton *imageView = self.scrollView.subviews[i - index + 1];
            [imageView setImage:[UIImage imageNamed:_imageArray[i]] forState:UIControlStateNormal];
        }
    }else if(self.imageArray.count - 1 == index){ //the last image
        //get the last ImageView
        FSButton *imageView = self.scrollView.subviews[mScrollerImageCount - 1];
        //set up the last iamge
        [imageView setImage:[UIImage imageNamed:_imageArray[0]] forState:UIControlStateNormal];
        //other image
        for (int i = index - 1; i < index - 1 + mScrollerImageCount - 1; i ++) {
            FSButton *imageView = self.scrollView.subviews[i - index + 1];
            [imageView setImage:[UIImage imageNamed:_imageArray[i]] forState:UIControlStateNormal];
        }
    }else  {
        for (int i = index - 1; i < index - 1 + mScrollerImageCount; i ++) {
            //get every ImageView
            FSButton *imageView = self.scrollView.subviews[i - index + 1];
            //setup every iamge
            [imageView setImage:[UIImage imageNamed:_imageArray[i]] forState:UIControlStateNormal];
        }
    }
    /*
    if (0 == index) {   //the first image
        //get the first ImageView
        UIImageView *imageView = self.scrollView.subviews[index];
        //set up the last iamge
        imageView.image = [UIImage imageNamed:_imageArray[self.imageArray.count - 1]];
        for (int i = 0; i< mScrollerImageCount - 1; i ++) {
            UIImageView *imageView = self.scrollView.subviews[i - index + 1];
            imageView.image = [UIImage imageNamed:_imageArray[i]];
        }
        
    }else if(self.imageArray.count - 1 == index){ //the last image
        //get the last ImageView
        UIImageView *imageView = self.scrollView.subviews[mScrollerImageCount - 1];
        //set up the last iamge
        imageView.image = [UIImage imageNamed:_imageArray[0]];
        //other image
        for (int i = index - 1; i < index - 1 + mScrollerImageCount - 1; i ++) {
            UIImageView *imageView = self.scrollView.subviews[i - index + 1];
            imageView.image = [UIImage imageNamed:_imageArray[i]];
        }
    }else  {
        for (int i = index - 1; i < index - 1 + mScrollerImageCount; i ++) {
            //get every ImageView
            UIImageView *imageView = self.scrollView.subviews[i - index + 1];
            //setup every iamge
            imageView.image = [UIImage imageNamed:_imageArray[i]];
        }
    }*/
    //default show the second image
    [self.scrollView setContentOffset:CGPointMake(mScrollerViewWidth, 0) animated:ani];
}

- (void)btnOnClick{
    FSLog(@"btnOnClick");
}

// when user dragging  the timer should be stoped
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [self stopTimer];
}
// when user stop to dragg the scrollview start the timer
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self startTimer];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    [self setCurrentImage:self.pageView.currentPage animate:NO];
}

#pragma mark - set about time
- (void)startTimer{
    if (self.timer) return;
    // init the time
    if (0 == self.time) {
        _time = 2.0f;
    }
    // 1.create a NSTimer
    self.timer = [NSTimer scheduledTimerWithTimeInterval:self.time target:self selector:@selector(nextPage) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
- (void)stopTimer
{
    [self.timer invalidate];
}
- (void)nextPage
{
    // calculate the next page
    NSInteger page = self.pageView.currentPage + 1;
    // if beyond the last page
    if (page == self.imageArray.count) page = 0;
    self.pageView.currentPage = page;
    // scroll to next page
    [self.scrollView setContentOffset:CGPointMake((mScrollerImageCount - 1) * mScrollerViewWidth, 0) animated:YES];
}

- (void)awakeFromNib{
    self.scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.pageView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin;
    self.scrollView.delegate = self;
    self.scrollView.pagingEnabled = YES;
    self.pageView.hidesForSinglePage = YES;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    // 6.start the timer
    //    [self startTimer];//如果在这里开始定时器会导致定时器的时间间隔一开始创建时无法调整
}

- (void)setTime:(double)time{
    _time = time;
    [self stopTimer];
    [self startTimer];
}
- (void)setPageControlCurrentImage:(NSString *)pageControlCurrentImage{
    [self.pageView setValue:[UIImage imageNamed:pageControlCurrentImage] forKeyPath:@"_currentPageImage"];
}
- (void)setPageControlImage:(NSString *)pageControlImage{
    [self.pageView setValue:[UIImage imageNamed:pageControlImage] forKeyPath:@"_pageImage"];
}

@end
